package com.z.pms1.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;


/**
 * @Title:
 * @Description:
 * @Copyright: 360buy 2012
 * @Date: Jan 29, 2013 2:16:02 PM
 * @author: caizhen
 * @version: 1.0
 */
public class BaseAction implements SessionAware, ServletRequestAware, ServletResponseAware{
	
	protected static final Log log = LogFactory.getLog(BaseAction.class.getName());

	protected Map<String, Object> session = null;
	
	protected HttpServletRequest request = null;
	
	protected HttpServletResponse response = null;
	
	/**
	 * print json string to response
	 * @param jsonStr
	 */
	protected void printToJson(String jsonStr) {
		try {
			log.info(jsonStr);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			out.println(jsonStr);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Transfer an object to string, then print the string to response
	 * @param o
	 */
	protected void printToJson(Object o) {
		String json = JSONObject.fromObject(o).toString();
		printToJson(json);
	}
	
	/**
	 * Transfer a List to string, then print the string to response
	 * @param list
	 */
	@SuppressWarnings("rawtypes")
	protected void printToJson(List list) {
		String json = JSONArray.fromObject(list).toString();
		printToJson(json);
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public Map<String, Object> getSession() {
		return session;
	}
	
	public HttpServletRequest getServletRequest() {
		return request;
	}
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletResponse getServletResponse() {
		return response;
	}

}
